package ac.zlf.springmybatis.core.mybatis.dialect;

import ac.zlf.springmybatis.core.mybatis.domain.PageRequest;
import org.apache.ibatis.mapping.MappedStatement;

public class SQLServer2005Dialect extends Dialect {
    public SQLServer2005Dialect(MappedStatement mappedStatement, Object parameterObject, PageRequest pageRequest) {
        super(mappedStatement, parameterObject, pageRequest);
    }

    protected String getLimitString(String sql, String offsetName, int offset, String limitName, int limit) {
        StringBuffer pagingBuilder = new StringBuffer();
        String orderby = getOrderByPart(sql);
        String distinctStr = "";

        String loweredString = sql.toLowerCase();
        String sqlPartString = sql;
        if (loweredString.trim().startsWith("select")) {
            int index = 6;
            if (loweredString.startsWith("select distinct")) {
                distinctStr = "DISTINCT ";
                index = 15;
            }
            sqlPartString = sqlPartString.substring(index);
        }
        pagingBuilder.append(sqlPartString);
        if ((orderby == null) || (orderby.length() == 0)) {
            orderby = "ORDER BY CURRENT_TIMESTAMP";
        }
        StringBuffer result = new StringBuffer();
        result.append("WITH query AS (SELECT ").append(distinctStr).append("TOP 100 PERCENT ").append(" ROW_NUMBER() OVER (").append(orderby).append(") as __row_number__, ").append(pagingBuilder).append(") SELECT * FROM query WHERE __row_number__ > ? AND __row_number__ <= ?").append(" ORDER BY __row_number__");


        setPageParameter(offsetName, Integer.valueOf(offset), Integer.class);
        setPageParameter("__offsetEnd", Integer.valueOf(offset + limit), Integer.class);
        return result.toString();
    }

    static String getOrderByPart(String sql) {
        String loweredString = sql.toLowerCase();
        int orderByIndex = loweredString.indexOf("order by");
        if (orderByIndex != -1) {
            return sql.substring(orderByIndex);
        }
        return "";
    }
}